package ascii

import (
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
	"time"
)

type TxtInfo struct {
	index   int    //排序字段
	content string //文本文件的内容
}

type PlayList []TxtInfo

func (pl PlayList) Less(i, j int) bool {
	return pl[i].index < pl[j].index
}

func (pl PlayList) Len() int {
	return len(pl)
}

func (pl PlayList) Swap(i, j int) {
	pl[i], pl[j] = pl[j], pl[i]
}

func Play(asciiDirectory string, fps int, base int) {
	//准备所有字符动画内容, 和排序
	var pl PlayList
	dirEntries, _ := os.ReadDir(asciiDirectory)
	for _, entry := range dirEntries {
		if entry.IsDir() {
			continue
		}
		filename := entry.Name()
		//删掉后缀名的名字
		name := filename[0:strings.LastIndex(filename, ".")]
		//文件的索引
		index, _ := strconv.Atoi(name)
		//文件路径
		filePath := asciiDirectory + "\\" + filename
		//读取文件
		content, _ := os.ReadFile(filePath)
		//文件对象
		txtInfo := TxtInfo{index, string(content)}
		pl = append(pl, txtInfo)
	}

	//排序
	sort.Sort(pl)

	//播放
	doPlayString(pl, fps, base)
}

func doPlayString(pl PlayList, fps int, base int) {
	interval := time.Duration(base/fps) * time.Millisecond
	for _, txtInfo := range pl {
		time.Sleep(interval)
		fmt.Print(txtInfo.content)
	}
}

// 58s  少1   900
// 70s 多10   950
